package com.tepth.remote.control.delegate.apply.create;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.AppCompatEditText;
import android.support.v7.widget.AppCompatTextView;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.tepth.remote.control.R;
import com.tepth.remote.control.R2;
import com.tepth.remote.control.base.bean.Project;
import com.tepth.remote.control.base.mvp.BaseMvpDelegate;
import com.tepth.remote.control.manager.ConfigManager;
import com.tepth.remote.ui.alert.DialogLoader;
import com.tepth.remote.ui.alert.IDialogClickListener;
import com.tepth.remote.ui.calendar.CustomDatePicker;

import org.angmarch.views.NiceSpinner;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Description:
 *
 * @author Hequn.Lee
 * @date 2018/11/24
 */
public class ApplyCreateDelegate extends BaseMvpDelegate<ApplyCreatePresenter> implements ApplyCreateContract.View {

    @BindView(R2.id.icon_toolbar_title)
    AppCompatTextView toolbarTitle = null;
    @BindView(R2.id.nice_spinner_project)
    NiceSpinner projectNiceSpinner = null;
    @BindView(R2.id.nice_spinner_examination)
    NiceSpinner examinationNiceSpinner = null;
    @BindView(R2.id.text_start_calendar)
    AppCompatTextView startCalendar = null;
    @BindView(R2.id.text_end_calendar)
    AppCompatTextView endCalendar = null;
    @BindView(R2.id.edit_reason)
    AppCompatEditText editReason = null;

    /**
     * 选中的项目ID
     */
    private int projectId = 0;
    /**
     * 选中的请假理由ID
     */
    private String examinationId = "";
    /**
     * 日期时间选择控件
     */
    private CustomDatePicker startCalendarPicker, endCalendarPicker;
    private static final SimpleDateFormat DEFAULT = new SimpleDateFormat(CustomDatePicker.DEFAULT_FORMAT, Locale.CHINA);
    /**
     * 默认开始时间
     */
    private static final String START_CALENDAR = TimeUtils.getStringByNow(-60, DEFAULT, TimeConstants.DAY);
    /**
     * 默认结束时间
     */
    private static final String END_CALENDAR = TimeUtils.getStringByNow(365, DEFAULT, TimeConstants.DAY);
    private DialogLoader mDialogLoader = null;

    @OnClick({R2.id.icon_toolbar_back, R2.id.text_start_calendar, R2.id.text_end_calendar, R2.id.linear_examination_submit})
    void onClick(View view) {
        final int id = view.getId();
        if (id == R.id.icon_toolbar_back) {
            pop();
        } else if (id == R.id.text_start_calendar) {
            startCalendarPicker.show(TimeUtils.getNowString(DEFAULT));
        } else if (id == R.id.text_end_calendar) {
            endCalendarPicker.show(TimeUtils.getStringByNow(1, DEFAULT, TimeConstants.DAY));
        } else if (id == R.id.linear_examination_submit) {
            submit();
        }
    }

    @Override
    public Object setLayout() {
        return R.layout.delegate_apply_create;
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        mDialogLoader = new DialogLoader(getProxyActivity());
        toolbarTitle.setText("请假申请");
        initProject();
        initCalendar();
        mPresenter.getExamination();
    }

    private void initProject() {
        final ArrayList<Project> allData = ConfigManager.getInstance().getProjects();
        final ArrayList<String> projectNames = new ArrayList<>();
        final int size = allData.size();
        for (int i = 0; i < size; i++) {
            projectNames.add(allData.get(i).getPro_Name());
        }
        if (size > 0) {
            projectId = allData.get(0).getPro_Id();
        }
        projectNiceSpinner.attachDataSource(projectNames);
        if (size < 2) {
            projectNiceSpinner.setOnTouchListener(new View.OnTouchListener() {
                @SuppressLint("ClickableViewAccessibility")
                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    ToastUtils.showShort("没有可选择的项目");
                    return true;
                }
            });
        } else {
            projectNiceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    projectId = allData.get(position).getPro_Id();
                }
            });
        }
    }

    private void initCalendar() {
        startCalendarPicker = new CustomDatePicker(getProxyActivity(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                startCalendar.setText(time);
            }
        }, START_CALENDAR, END_CALENDAR);
        endCalendarPicker = new CustomDatePicker(getProxyActivity(), new CustomDatePicker.ResultHandler() {
            @Override
            public void handle(String time) {
                endCalendar.setText(time);
            }
        }, START_CALENDAR, END_CALENDAR);
        startCalendarPicker.showSpecificTime(true);
        endCalendarPicker.showSpecificTime(true);
        startCalendarPicker.setIsLoop(true);
        endCalendarPicker.setIsLoop(true);
    }

    private void submit() {
        final String startDate = startCalendar.getText().toString();
        final String endDate = endCalendar.getText().toString();
        if (startDate.length() == 0) {
            mDialogLoader.showFailed("请选择请假开始时间", "", new IDialogClickListener() {
                @Override
                public void onClick() {
                    mDialogLoader.clearDialog();
                }
            });
            return;
        }
        if (endDate.length() == 0) {
            mDialogLoader.showFailed("请选择请假结束时间", "", new IDialogClickListener() {
                @Override
                public void onClick() {
                    mDialogLoader.clearDialog();
                }
            });
            return;
        }
        if (TimeUtils.getTimeSpan(startDate, endDate, DEFAULT, TimeConstants.MIN) > 0) {
            mDialogLoader.showFailed("请假时间有误，请重新选择", "", new IDialogClickListener() {
                @Override
                public void onClick() {
                    mDialogLoader.clearDialog();
                }
            });
            return;
        }
        String reason = "";
        if (editReason != null && editReason.getText() != null) {
            reason = editReason.getText().toString();
        }
        mPresenter.submitApply(projectId, examinationId, startDate, endDate, reason);
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, View rootView) {

    }

    @Override
    public ApplyCreatePresenter getPresenter() {
        return new ApplyCreatePresenter(this);
    }

    @Override
    public void getExaminationSuccess(WeakHashMap<String, String> result) {
        mDialogLoader.clearDialog();
        final ArrayList<String> examinationNameList = new ArrayList<>();
        final ArrayList<String> examinationIdList = new ArrayList<>();
        for (WeakHashMap.Entry entry : result.entrySet()) {
            // 获取key
            examinationIdList.add((String) entry.getKey());
            // 获取value
            examinationNameList.add((String) entry.getValue());
        }
        if (examinationIdList.size() > 0) {
            examinationId = examinationIdList.get(0);
        }
        if(examinationNiceSpinner!=null){
            examinationNiceSpinner.attachDataSource(examinationNameList);
            if (examinationNameList.size() < 2) {
                examinationNiceSpinner.setOnTouchListener(new View.OnTouchListener() {
                    @SuppressLint("ClickableViewAccessibility")
                    @Override
                    public boolean onTouch(View v, MotionEvent event) {
                        ToastUtils.showShort("没有可选择的项目");
                        return true;
                    }
                });
            } else {
                examinationNiceSpinner.addOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                        examinationId = examinationIdList.get(position);
                    }
                });
            }
        }
    }

    @Override
    public void getExaminationFailed(int code, String msg) {
        mDialogLoader.stopProgressWithFailed("获取请假配置信息失败", "", new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                mPresenter.getExamination();
            }
        });
    }

    @Override
    public void submitApplySuccess() {
        mDialogLoader.stopProgressWithSuccess("申请提交成功", "", new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
                pop();
            }
        });
    }

    @Override
    public void submitApplyFailed(int code, String msg) {
        mDialogLoader.stopProgressWithFailed("申请提交失败", "", new IDialogClickListener() {
            @Override
            public void onClick() {
                mDialogLoader.clearDialog();
            }
        });
    }

    @Override
    public void showLoading(String str) {
        mDialogLoader.showProgressDialog(false, str, "");
    }

    @Override
    public void hideLoading() {

    }
}
